import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginPage.vue')
    },
    {
      path: '/:catchAll(.*)',
      component: () => import('@/views/NotFound404.vue')
    }
    // {
    //   path: '/appContext',
    //   name: 'appContext',
    //   component: () => import('../views/AppPage.vue'),
    //   redirect:'/home',
    //   children: [
    //     {
    //       path: '/home',
    //       name: 'home',
    //       component: () => import('../views/HomeView.vue')
    //     },
    //     {
    //       path: '/about',
    //       component: () => import('../views/AboutView.vue')
    //     },
    //     {
    //       path: '/some',
    //       component: () => import('../views/SomeView.vue')
    //     },
    //     {
    //       path: '/pra',
    //       component: () => import('../views/PraView.vue')
    //     }
    //   ]
    // }
  ]
})

import { useMenuStore } from '@/stores/menu'
import { findAllMenus, loadUserInfo, loadDicts } from './init'
const whiteList = ['/login', '/']
router.beforeEach(async (to, from, next) => {
  const store = useMenuStore()
  // console.log(' router is routing ', from, to)
  // lin shi findMenusbyToken
  if (whiteList.includes(to.path)) {
    next()
  } else {
    if (!store.token) {
      next('/login')
    } else {
      // next()
      if (store.appFlushed) {
        next()
      } else {
        await loadUserInfo()
        await findAllMenus()
        await loadDicts()
        store.appFlushed = true
        next(to)
        // next();
      }
    }
  }
})

export default router
